package com.lhcai.lc.other;

/**
 * @author lhcstart
 * @create 2023-02-25 19:21
 */

/**
 * 合并两个排序的链表
 * 输入两个递增排序的链表，合并这两个链表并使新链表中的节点仍然是递增排序的
 */
public class JZ25 {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

        //辅助链表
        ListNode dum = new ListNode(0);
        ListNode cur = dum;
        while (l1 != null && l2 != null) {
            //l1小，将l1链接到cur后，并且l1指针后移
            if (l1.val < l2.val) {
                cur.next = l1;
                l1 = l1.next;
            } else {
                //l2小，将l2链接到cur后，并且l2指针后移
                cur.next = l2;
                l2 = l2.next;
            }
            //cur指针后移
            cur = cur.next;
        }
        //判断哪个为空，将不空的链接到cur后
        cur.next = l1 != null ? l1 : l2;
        return dum.next;

    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }
}
